import { defineStore } from "pinia";

export const useToastStore = defineStore(
	"toast",
	() => {
		const toastBox = ref();

		const toastState = reactive({
			message: null,
			type: "success",
		});

		const setToastBox = (v) => (toastBox.value = v);

		const setToast = (message, type: "success" | "error" | "warning") => {
			toastState.message = message;
			toastState.type = type;
		};

		watch(
			() => toastState.message,
			(val) => {
				if (val) {
					toastBox.value?.close();
					toastBox.value?.[toastState.type]?.({ msg: val, duration: 3000 });

					setTimeout(() => {
						toastBox.value?.close();
						toastState.message = null;
					}, 3000);
				}
			},
		);

		return {
			register: setToastBox,
			set: setToast,
		};
	},
	{
		persist: true,
	},
);
